import os
import shutil
import sys

def clear_pycache(directory):
    """
    递归删除指定目录下的所有 __pycache__ 文件夹
    
    Args:
        directory (str): 要清理的目录路径
    """
    count = 0
    total_size = 0
    
    print(f"开始清理 {directory} 目录下的 __pycache__ 文件夹...")
    
    for root, dirs, files in os.walk(directory):
        if "__pycache__" in dirs:
            pycache_path = os.path.join(root, "__pycache__")
            try:
                # 计算文件夹大小
                folder_size = sum(os.path.getsize(os.path.join(dirpath, filename)) 
                                 for dirpath, _, filenames in os.walk(pycache_path)
                                 for filename in filenames)
                
                # 删除文件夹
                shutil.rmtree(pycache_path)
                
                total_size += folder_size
                count += 1
                print(f"已删除: {pycache_path} ({folder_size/1024:.2f} KB)")
            except Exception as e:
                print(f"删除 {pycache_path} 时出错: {e}")
    
    print(f"\n清理完成!")
    print(f"共删除了 {count} 个 __pycache__ 文件夹")
    print(f"释放空间: {total_size/1024/1024:.2f} MB")

if __name__ == "__main__":
    # 获取当前脚本所在目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    
    # 清理当前目录下的 __pycache__ 文件夹
    clear_pycache(current_dir)
